import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, LoginRequest, RegisterRequest } from '@/types/auth'
import { authApi } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'

export const useAuthStore = defineStore('auth', () => {
  // State
  const user = ref<User | null>(null)
  const token = ref<string | null>(getToken())
  const loading = ref(false)

  // Getters
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  const isAdmin = computed(() => user.value?.role === 'admin')

  // Actions
  const login = async (credentials: LoginRequest) => {
    loading.value = true
    try {
      const response = await authApi.login(credentials)
      const { token: authToken, user: userData } = response.data
      
      token.value = authToken
      user.value = userData
      setToken(authToken)
      
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  const register = async (userData: RegisterRequest) => {
    loading.value = true
    try {
      const response = await authApi.register(userData)
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  const logout = async () => {
    try {
      await authApi.logout()
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      user.value = null
      token.value = null
      removeToken()
    }
  }

  const refreshToken = async () => {
    try {
      const response = await authApi.refreshToken()
      const { token: newToken } = response.data
      
      token.value = newToken
      setToken(newToken)
      
      return response
    } catch (error) {
      // If refresh fails, logout user
      await logout()
      throw error
    }
  }

  const fetchUserProfile = async () => {
    try {
      const response = await authApi.getProfile()
      user.value = response.data
      return response
    } catch (error) {
      throw error
    }
  }

  const updateProfile = async (profileData: Partial<User>) => {
    try {
      const response = await authApi.updateProfile(profileData)
      user.value = { ...user.value, ...response.data }
      return response
    } catch (error) {
      throw error
    }
  }

  // Initialize auth state
  const initialize = async () => {
    if (token.value) {
      try {
        await fetchUserProfile()
      } catch (error) {
        // If profile fetch fails, clear auth state
        await logout()
      }
    }
  }

  return {
    // State
    user,
    token,
    loading,
    
    // Getters
    isAuthenticated,
    isAdmin,
    
    // Actions
    login,
    register,
    logout,
    refreshToken,
    fetchUserProfile,
    updateProfile,
    initialize
  }
})